<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1200" destroy-on-close @closed="$emit('closed')">
        <el-form :model="entityObj" :rules="rules" :disabled="mode == 'Show'" ref="dialogForm" label-width="100px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="采购订单编号:">
                        <el-tooltip placement="top" v-for="(item,index) in entityObj.purchaseOrders" :key="item.purchaseOrderId">
                            <template #content>
                                要货单位: {{item.storeName}}
                                <br />
                                申请人:{{item.purchaseName}}
                                <br />
                                申请时间:{{item.purchaseDate}}
                                <br />
                                期望到货时间:{{item.expectedDate}}
                                <br />
                                发货状态:{{item.sendStatusDesc}}
                            </template>
                            <span style="color: blue;margin-right: 5px;" >{{item.purchaseOrderCode}}{{ index !== entityObj.purchaseOrders.length - 1 ? ',' : '' }}  </span>
                        </el-tooltip>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="出库时间:" prop="sendDate">
						<el-date-picker
						    v-model="entityObj.sendDate"
						    type="datetime"
						    value-format="YYYY-MM-DD HH:mm:ss"
						    format="YYYY-MM-DD HH:mm:ss"
						/>
                      <!--  <el-input v-model="entityObj.sendDate" /> -->
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="物流公司:" >
                        <el-select placeholder="---请选择物流公司---" v-model="entityObj.logisticsId" style="width: 100%">
                            <el-option label="---请选择---" value />
                            <el-option v-for="item in optionsLogistics" :key="item.logisticsId" :label="item.logisticsName"
                                :value="item.logisticsId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="155px" label="配送物流单号/车牌:">
                        <el-input v-model="entityObj.logisticsCode" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="155px" label="备注">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="155px" label="附件上传" >
                        <sc-upload-file v-model="entityObj.sendFiles" :objName="'Supply/sendOrder'" draggable
                            :uploadType="'OSS'" :bucketName="'jtmc'" :limit="9" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="155px" label="出库发货:">
                        <el-form inline label-width="49px" style="margin-top: 5px">
                            <el-form-item label="物料编号" label-width="80px">
                                <el-input placeholder="---请输入编号---" v-model="queryList.materialCode" style="width: 160px" />
                            </el-form-item>
                            <el-form-item label="物料名称" label-width="80px">
                                <el-input placeholder="---请输入名称---" v-model="queryList.materialName" style="width: 160px" />
                            </el-form-item>
                            <el-form-item label="物料分类" label-width="80px">
                                <el-tree-select v-model="queryList.materialTypeIds"
                                    placeholder="---请选择物料分类---"
                                    collapse-tags
                                    collapse-tags-tooltip
                                    :props="{ label: 'label', value: 'value', children: 'children' }" :data="materialTypeTree"
                                    multiple :render-after-expand="false" show-checkbox style="width: 160px" />
                            </el-form-item>
                            <el-button :icon="Search"   type="primary"
                                @click="handleSearch">查询</el-button>
                            <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                            <el-form inline label-width="49px" style="margin-top: 5px"></el-form>
                        </el-form>
                        <el-table :data="itemsData" border style="width: 100%" show-summary :summary-method="getSummaries">
                            <el-table-column label="物料编码" width="110" prop="materialCode">
                            </el-table-column>
                            <el-table-column label="物料名称" width="140" prop="materialName">
                            </el-table-column>
                            <el-table-column label="规格" width="100" prop="materialSpecs">
                            </el-table-column>
                            <el-table-column label="物料类别" width="85" prop="materialTypeName">
                            </el-table-column>
                            <el-table-column label="单位" width="70" prop="unitName">
                            </el-table-column>
                            <el-table-column label="类型" width="70" prop="purchaseOrderTypeDesc">
                            </el-table-column>
                            <el-table-column label="配送数量" width="85" prop="receiveQty">
                            </el-table-column>
                            <el-table-column label="累计配送" width="85" prop="sendQty">
                            </el-table-column>
                            <el-table-column label="累计退货" width="85" prop="returnedQty">
                            </el-table-column>
                            <el-table-column label="配送单价" width="90" prop="price">
                            </el-table-column>
                            <el-table-column label="配送金额" width="90" prop="totalAmount">
                            </el-table-column>
                            <el-table-column label="备注" width="140" prop="remarks">
                            </el-table-column>
                            <el-table-column label="出库仓库" width="140" prop="warehouseId">
                                <template #default="scope">
                                    <el-select :disabled="scope.row.sendQty>=scope.row.receiveQty" placeholder="---请选择出库仓库 ---" v-model="scope.row.warehouseId"
                                        style="width: 100%">
                                        <el-option label="---请选择---" value />
                                        <el-option v-for="item in scope.row.warehouses" :key="item.warehouseId"
                                            :label="item.warehouseName" :value="item.warehouseId" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="出库数量" width="140">
                                <template #default="scope">
                                    <el-input-number :disabled="scope.row.sendQty>=scope.row.receiveQty" v-model="scope.row.qty" style="width: 100%" :precision="0" :step="1"
                                        controls-position="right"></el-input-number>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">确认出库发货</el-button>
        </template>

        <!-- <template>
            <el-dialog v-model="materialState" title="选择商品" :width="1000" :center="true" append-to-body
                style="height: 480px">
                <el-row>
                    <sc-material-choice ref="scMaterialChoice"></sc-material-choice>
                </el-row>
                <template #footer>
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template> -->
    </el-dialog>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Send",
            titleMap: {
                Send: "发货",
            },
            entityObj: {
            },
            materialState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                sendDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                logisticsId: [
                    { required: true, type: "number", message: "请填写" },
                ],
                logisticsCode: [
                    { required: true, type: "string", message: "请填写" },
                ],
            },
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsLogistics: [],
            itemsData: [],
        };
    },
    computed: {
        // itemsData() {
        //     let filtered = this.entityObj.purchaseProtocolItems;
        //     if (this.queryList.materialTypeIds&&this.queryList.materialTypeIds.length>0) {
        //         filtered = filtered.filter(item => {
        //             return this.queryList.materialTypeIds.includes(item.materialTypeId);
        //         });
        //     }
        //     if (this.queryList.materialCode) {
        //         filtered = filtered.filter(item => {
        //             return item.materialCode.includes(this.queryList.materialCode);
        //         });
        //     }
        //     if (this.queryList.materialName) {
        //         filtered = filtered.filter(item => {
        //             return item.materialName.includes(this.queryList.materialName);
        //         });
        //     }
        //     return filtered;
        // },
    },
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post("purchase-order/send",
                                { ...this.entityObj ,logisticsName:this.optionsLogistics.find(p=>p.logisticsId==this.entityObj.logisticsId)?.logisticsName}
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(data) {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "purchase-order/send-detail",
                    { purchaseOrderIds: data }
                );
                if (returnValue.status == 200) {
                    this.entityObj = { ...returnValue.response, logisticsId: null, logisticsCode: "", sendDate: tool.formatDate(new Date()) };
                    this.queryList = {};
                    this.handleSearch();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "material-type/tree",
                    { status: 1 }
                );
                if (returnValue.status == 200) {
                    this.materialTypeTree = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "logistics/current",
                    { }
                );
                if (returnValue.status == 200) {
                    this.optionsLogistics = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        handleSearch() {
            this.itemsData = this.entityObj.sendOrderItems;
            if (
                this.queryList.materialTypeIds &&
                this.queryList.materialTypeIds.length > 0
            ) {
                this.itemsData = this.itemsData.filter((item) => {
                    return this.queryList.materialTypeIds.includes(
                        item.materialTypeId
                    );
                });
            }

            if (this.queryList.materialCode) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialCode.includes(
                        this.queryList.materialCode
                    );
                });
            }

            if (this.queryList.materialName) {
                this.itemsData = this.itemsData.filter((item) => {
                    return item.materialName.includes(
                        this.queryList.materialName
                    );
                });
            }
            console.log(this.entityObj.purchaseProtocolItems);
        },

        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        getSummaries(param){
            const{ columns,data}=param;
            const sums=[];
            columns.forEach((column,index)=>{
                if (index === 0) {
                    sums[index] = '合计'
                    return;
                }
                const values=data.map(item=>Number(item[column.property]));

                if(column.property=='receiveQty' || column.property=='sendQty' || column.property=='returnedQty'|| column.property=='price'|| column.property=='totalAmount'){
                    if(!values.every(item=>isNaN(item))){
                        const total = values.reduce((a, b) => a + b, 0)
                        sums[index] = total
                    }
                }
            });
            return sums;
        },
    },
    async mounted() {
        await this.initOptions();
    },
};
</script>

<style scoped>
.el-form-item {
    margin-bottom: 8px !important;
}
</style>
